'use client';

import React, { useState } from 'react';
import Button from '@/components/ui/Button';
import { 
  Plus,
  TrendingDown,
  BarChart3,
  Download,
  Eye,
  Play,
  AlertTriangle,
  CheckCircle,
  Users, 
  Camera,
  Activity,
  TrendingUp,
  Clock,
  FileText,
  Target,
  Zap
} from 'lucide-react';

interface EvaluationTask {
  id: string;
  name: string;
  type: 'auto' | 'manual';
  status: 'pending' | 'running' | 'completed' | 'failed';
  modelName: string;
  datasetName: string;
  forgettingRate: number;
  accuracy: number;
  baselineAccuracy: number;
  createdAt: string;
  completedAt?: string;
  metrics: {
    precision: number;
    recall: number;
    f1Score: number;
  };
  categories: {
    workerRecognition: number;
    defectDetection: number;
    environmentHazard: number;
  };
}

interface EvaluationDataset {
  id: string;
  name: string;
  category: string;
  version: string;
  samples: number;
  status: 'active' | 'archived';
  lastUsed: string;
}

export default function EvaluationsPage() {
  const [activeTab, setActiveTab] = useState<'tasks' | 'datasets' | 'reports'>('tasks');
  
  const [evaluationTasks] = useState<EvaluationTask[]>([
    {
      id: '1',
      name: '人员作业识别遗忘评估',
      type: 'auto',
      status: 'completed',
      modelName: 'PowerVision-Workers v2.3.1',
      datasetName: '人员作业评估集v1.2',
      forgettingRate: 8.3,
      accuracy: 91.7,
      baselineAccuracy: 94.8,
      createdAt: '2024-12-02 14:30:00',
      completedAt: '2024-12-02 16:45:00',
      metrics: {
        precision: 92.1,
        recall: 91.3,
        f1Score: 91.7
      },
      categories: {
        workerRecognition: 7.2,
        defectDetection: 9.1,
        environmentHazard: 8.8
      }
    },
    {
      id: '2',
      name: '设备缺陷识别遗忘测试',
      type: 'auto',
      status: 'running',
      modelName: 'PowerNet-Defect v1.8.2',
      datasetName: '设备缺陷评估集v2.0',
      forgettingRate: 0,
      accuracy: 0,
      baselineAccuracy: 91.2,
      createdAt: '2024-12-03 09:15:00',
      metrics: {
        precision: 0,
        recall: 0,
        f1Score: 0
      },
      categories: {
        workerRecognition: 0,
        defectDetection: 0,
        environmentHazard: 0
      }
    },
    {
      id: '3',
      name: '环境隐患识别评估',
      type: 'manual',
      status: 'pending',
      modelName: 'PowerGuard-Environment v3.1.0',
      datasetName: '环境隐患评估集v1.5',
      forgettingRate: 0,
      accuracy: 0,
      baselineAccuracy: 89.5,
      createdAt: '2024-12-03 11:00:00',
      metrics: {
        precision: 0,
        recall: 0,
        f1Score: 0
      },
      categories: {
        workerRecognition: 0,
        defectDetection: 0,
        environmentHazard: 0
      }
    },
    {
      id: '4',
      name: '序列缺陷检测遗忘度评估',
      type: 'auto',
      status: 'failed',
      modelName: 'PowerSeq-Defect v2.1.3',
      datasetName: '时序数据评估集v1.0',
      forgettingRate: 0,
      accuracy: 0,
      baselineAccuracy: 78.9,
      createdAt: '2024-12-02 20:00:00',
      metrics: {
        precision: 0,
        recall: 0,
        f1Score: 0
      },
      categories: {
        workerRecognition: 0,
        defectDetection: 0,
        environmentHazard: 0
      }
    }
  ]);

  const [evaluationDatasets] = useState<EvaluationDataset[]>([
    {
      id: '1',
      name: '人员作业评估集',
      category: '人员识别',
      version: 'v1.2',
      samples: 2840,
      status: 'active',
      lastUsed: '2024-12-02'
    },
    {
      id: '2',
      name: '设备缺陷评估集',
      category: '缺陷检测',
      version: 'v2.0',
      samples: 4620,
      status: 'active',
      lastUsed: '2024-12-03'
    },
    {
      id: '3',
      name: '环境隐患评估集',
      category: '环境隐患',
      version: 'v1.5',
      samples: 1890,
      status: 'active',
      lastUsed: '2024-11-28'
    },
    {
      id: '4',
      name: '时序数据评估集',
      category: '序列分析',
      version: 'v1.0',
      samples: 1240,
      status: 'archived',
      lastUsed: '2024-11-15'
    }
  ]);

  const [selectedScenario, setSelectedScenario] = useState('personnel_recognition');

  const scenarios = [
    {
      id: 'personnel_recognition',
      name: '人员作业识别',
      type: 'image',
      baseline_accuracy: 0.80,
      current_accuracy: 0.88,
      target_improvement: 0.10,
      icon: Users,
      description: '电力作业人员安全监控'
    },
    {
      id: 'defect_detection',
      name: '设备缺陷检测',
      type: 'image',
      baseline_accuracy: 0.75,
      current_accuracy: 0.82,
      target_improvement: 0.15,
      icon: Camera,
      description: '电力设备外观缺陷识别'
    },
    {
      id: 'environment_hazard',
      name: '环境隐患识别',
      type: 'mixed',
      baseline_accuracy: 0.70,
      current_accuracy: 0.78,
      target_improvement: 0.20,
      icon: AlertTriangle,
      description: '电力设施环境安全隐患'
    }
  ];

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          <span className="w-1.5 h-1.5 bg-gray-600 rounded-full mr-1.5"></span>
          待执行
        </span>;
      case 'running':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mr-1.5 animate-pulse"></span>
          运行中
        </span>;
      case 'completed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          已完成
        </span>;
      case 'failed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          失败
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  const getTypeBadge = (type: string) => {
    switch (type) {
      case 'auto':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <Zap className="w-3 h-3 mr-1" />
          自动
        </span>;
      case 'manual':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800 border border-orange-200">
          <Users className="w-3 h-3 mr-1" />
          手动
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {type}
        </span>;
    }
  };

  const getForgettingRateColor = (rate: number) => {
    if (rate <= 5) return 'text-green-600';
    if (rate <= 10) return 'text-yellow-600';
    return 'text-red-600';
  };

  const getForgettingRateIcon = (rate: number) => {
    if (rate <= 5) return <TrendingUp className="h-4 w-4 text-green-600" />;
    if (rate <= 10) return <TrendingDown className="h-4 w-4 text-yellow-600" />;
    return <TrendingDown className="h-4 w-4 text-red-600" />;
  };

  // 统计数据
  const stats = {
    total: evaluationTasks.length,
    completed: evaluationTasks.filter(t => t.status === 'completed').length,
    running: evaluationTasks.filter(t => t.status === 'running').length,
    failed: evaluationTasks.filter(t => t.status === 'failed').length,
    avgForgettingRate: evaluationTasks.filter(t => t.status === 'completed').reduce((sum, t) => sum + t.forgettingRate, 0) / evaluationTasks.filter(t => t.status === 'completed').length || 0,
    avgAccuracy: evaluationTasks.filter(t => t.status === 'completed').reduce((sum, t) => sum + t.accuracy, 0) / evaluationTasks.filter(t => t.status === 'completed').length || 0
  };

  const renderTasksTab = () => (
    <div className="space-y-4">
      <div className="divide-y divide-gray-200">
        {evaluationTasks.map((task) => (
          <div key={task.id} className="p-4 hover:bg-gray-50 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-2">
                  <h3 className="text-lg font-medium text-gray-900">{task.name}</h3>
                  {getStatusBadge(task.status)}
                  {getTypeBadge(task.type)}
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                  <div>
                    <span className="text-sm text-gray-500">模型:</span>
                    <span className="ml-2 text-sm font-medium text-gray-900">{task.modelName}</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-500">数据集:</span>
                    <span className="ml-2 text-sm font-medium text-gray-900">{task.datasetName}</span>
                  </div>
                </div>
                
                {task.status === 'completed' && (
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-3">
                    <div className="text-center p-3 bg-red-50 border border-red-200 rounded-lg">
                      <div className="flex items-center justify-center mb-1">
                        {getForgettingRateIcon(task.forgettingRate)}
                      </div>
                      <div className={`text-lg font-bold ${getForgettingRateColor(task.forgettingRate)}`}>
                        {task.forgettingRate.toFixed(1)}%
                      </div>
                      <div className="text-xs text-gray-600">遗忘率</div>
                    </div>
                    
                    <div className="text-center p-3 bg-green-50 border border-green-200 rounded-lg">
                      <div className="flex items-center justify-center mb-1">
                        <Target className="h-4 w-4 text-green-600" />
                      </div>
                      <div className="text-lg font-bold text-green-600">
                        {task.accuracy.toFixed(1)}%
                      </div>
                      <div className="text-xs text-gray-600">当前准确率</div>
                    </div>
                    
                    <div className="text-center p-3 bg-blue-50 border border-blue-200 rounded-lg">
                      <div className="flex items-center justify-center mb-1">
                        <BarChart3 className="h-4 w-4 text-blue-600" />
                      </div>
                      <div className="text-lg font-bold text-blue-600">
                        {task.metrics.precision.toFixed(1)}%
                      </div>
                      <div className="text-xs text-gray-600">精确率</div>
                    </div>
                    
                    <div className="text-center p-3 bg-purple-50 border border-purple-200 rounded-lg">
                      <div className="flex items-center justify-center mb-1">
                        <Activity className="h-4 w-4 text-purple-600" />
                      </div>
                      <div className="text-lg font-bold text-purple-600">
                        {task.metrics.f1Score.toFixed(1)}%
                      </div>
                      <div className="text-xs text-gray-600">F1分数</div>
                    </div>
                  </div>
                )}
                
                <div className="flex items-center gap-4 text-xs text-gray-500">
                  <span>创建: {task.createdAt}</span>
                  {task.completedAt && <span>完成: {task.completedAt}</span>}
                  <span>基线准确率: {task.baselineAccuracy}%</span>
                </div>
              </div>
              
              <div className="flex items-center gap-2 ml-4">
                <button className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-md transition-colors">
                  <Eye className="h-4 w-4" />
                </button>
                {task.status === 'completed' && (
                  <button className="p-2 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-md transition-colors">
                    <Download className="h-4 w-4" />
                  </button>
                )}
                {task.status === 'pending' && (
                  <button className="p-2 text-gray-400 hover:text-orange-600 hover:bg-orange-50 rounded-md transition-colors">
                    <Play className="h-4 w-4" />
                  </button>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  const renderDatasetsTab = () => (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {evaluationDatasets.map((dataset) => (
          <div key={dataset.id} className="p-4 border border-gray-200 rounded-lg hover:shadow-md transition-shadow">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-medium text-gray-900">{dataset.name}</h3>
              <span className={`px-2 py-1 text-xs rounded-full ${
                dataset.status === 'active' 
                  ? 'bg-green-100 text-green-800' 
                  : 'bg-gray-100 text-gray-800'
              }`}>
                {dataset.status === 'active' ? '活跃' : '已归档'}
              </span>
            </div>
            
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">分类:</span>
                <span className="font-medium">{dataset.category}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">版本:</span>
                <span className="font-medium">{dataset.version}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">样本数:</span>
                <span className="font-medium">{dataset.samples.toLocaleString()}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">最后使用:</span>
                <span className="font-medium">{dataset.lastUsed}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  const renderReportsTab = () => (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {scenarios.map((scenario) => {
          const IconComponent = scenario.icon;
          return (
            <div 
              key={scenario.id}
              className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                selectedScenario === scenario.id
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
              onClick={() => setSelectedScenario(scenario.id)}
            >
              <div className="flex items-center mb-3">
                <IconComponent className={`h-5 w-5 mr-2 ${
                  selectedScenario === scenario.id ? 'text-blue-600' : 'text-gray-500'
                }`} />
                <h3 className="font-medium text-gray-900">{scenario.name}</h3>
              </div>
              
              <p className="text-sm text-gray-600 mb-3">{scenario.description}</p>
              
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">基线准确率:</span>
                  <span className="font-medium">{(scenario.baseline_accuracy * 100).toFixed(1)}%</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">当前准确率:</span>
                  <span className="font-medium text-green-600">{(scenario.current_accuracy * 100).toFixed(1)}%</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">目标提升:</span>
                  <span className="font-medium text-blue-600">+{(scenario.target_improvement * 100).toFixed(1)}%</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      
      {selectedScenario && (
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            {scenarios.find(s => s.id === selectedScenario)?.name} - 详细报告
          </h3>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h4 className="font-medium text-gray-900 mb-3">性能趋势</h4>
              <div className="h-32 bg-gray-100 rounded-lg flex items-center justify-center">
                <span className="text-gray-500">性能趋势图表</span>
              </div>
            </div>
            
            <div>
              <h4 className="font-medium text-gray-900 mb-3">遗忘率分析</h4>
              <div className="h-32 bg-gray-100 rounded-lg flex items-center justify-center">
                <span className="text-gray-500">遗忘率分析图表</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );

  return (
    <div className="space-y-4">
      {/* 紧凑的标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">遗忘评测</h1>
          <p className="text-sm text-gray-600 mt-0.5">模型遗忘度评估与性能分析</p>
        </div>
        <Button variant="primary" size="sm">
          <Plus className="h-4 w-4 mr-1.5" />
          新建评测
        </Button>
      </div>

      {/* 紧凑的统计卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
        <div className="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-blue-700 uppercase tracking-wide">总评测</div>
              <div className="text-2xl font-bold text-blue-900 mt-1">{stats.total}</div>
            </div>
            <BarChart3 className="h-6 w-6 text-blue-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">已完成</div>
              <div className="text-2xl font-bold text-green-900 mt-1">{stats.completed}</div>
            </div>
            <CheckCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 border border-yellow-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-yellow-700 uppercase tracking-wide">运行中</div>
              <div className="text-2xl font-bold text-yellow-900 mt-1">{stats.running}</div>
            </div>
            <Activity className="h-6 w-6 text-yellow-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-red-50 to-red-100 border border-red-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-red-700 uppercase tracking-wide">失败</div>
              <div className="text-2xl font-bold text-red-900 mt-1">{stats.failed}</div>
            </div>
            <AlertTriangle className="h-6 w-6 text-red-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-purple-50 to-purple-100 border border-purple-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-purple-700 uppercase tracking-wide">平均遗忘率</div>
              <div className="text-2xl font-bold text-purple-900 mt-1">{stats.avgForgettingRate.toFixed(1)}%</div>
            </div>
            <TrendingDown className="h-6 w-6 text-purple-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-orange-50 to-orange-100 border border-orange-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-orange-700 uppercase tracking-wide">平均准确率</div>
              <div className="text-2xl font-bold text-orange-900 mt-1">{stats.avgAccuracy.toFixed(1)}%</div>
            </div>
            <Target className="h-6 w-6 text-orange-600" />
          </div>
        </div>
      </div>

      {/* 选项卡导航 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
        <div className="flex border-b border-gray-200">
          {[
            { key: 'tasks', label: '评测任务', icon: BarChart3 },
            { key: 'datasets', label: '评测数据集', icon: FileText },
            { key: 'reports', label: '分析报告', icon: TrendingUp }
          ].map((tab) => {
            const IconComponent = tab.icon;
            return (
              <button
                key={tab.key}
                                 onClick={() => setActiveTab(tab.key as 'tasks' | 'datasets' | 'reports')}
                className={`flex items-center px-6 py-4 text-sm font-medium transition-colors ${
                  activeTab === tab.key
                    ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                }`}
              >
                <IconComponent className="h-4 w-4 mr-2" />
                {tab.label}
              </button>
            );
          })}
        </div>

        <div className="p-6">
          {activeTab === 'tasks' && renderTasksTab()}
          {activeTab === 'datasets' && renderDatasetsTab()}
          {activeTab === 'reports' && renderReportsTab()}
        </div>
      </div>

      {/* 底部统计汇总 */}
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">{evaluationTasks.length}</div>
            <div className="text-gray-600">总评测任务</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">{evaluationTasks.filter(t => t.status === 'completed').length}</div>
            <div className="text-gray-600">成功完成</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{evaluationDatasets.filter(d => d.status === 'active').length}</div>
            <div className="text-gray-600">活跃数据集</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">{scenarios.length}</div>
            <div className="text-gray-600">评测场景</div>
          </div>
        </div>
      </div>
    </div>
  );
} 